package dao

import (
	"context"

	"gorm.io/gorm/clause"

	"open/internal/model"
)

// CreateBrandMiniAppRef 保存品牌小程序关联
func (d *Dao) CreateBrandMiniAppRef(ctx context.Context, brandApp *model.BrandMiniApp) error {
	return d.FromContext(ctx).Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "brand_id"}, {Name: "platform"}, {Name: "deleted_at"}},
		UpdateAll: true,
	}).Create(brandApp).Error
}

// GetAppIDByBrandID 根据品牌ID获取AppID
func (d *Dao) GetAppIDByBrandID(ctx context.Context, brandID int64, platform int32) (string, error) {
	app := new(model.BrandMiniApp)
	err := d.FromContext(ctx).Where("brand_id = ? AND platform = ?", brandID, platform).First(app).Error
	if err != nil {
		return "", err
	}
	return app.AppID, nil
}

// GetBrandIDByAppID 根据AppID获取品牌ID
func (d *Dao) GetBrandIDByAppID(ctx context.Context, appID string, platform int32) (int64, error) {
	app := new(model.BrandMiniApp)
	err := d.FromContext(ctx).Where("app_id = ? AND platform = ?", appID, platform).First(app).Error
	if err != nil {
		return 0, err
	}
	return app.BrandID, nil
}

// GetBrandIDByAppID 根据AppID获取品牌ID
func (d *Dao) GetBrandMiniAppRef(ctx context.Context, brandID int64, appID string, platform int32) (*model.BrandMiniApp, error) {
	app := new(model.BrandMiniApp)
	err := d.FromContext(ctx).Where("brand_id = ? AND app_id = ? AND platform = ?", brandID, appID, platform).First(app).Error
	if err != nil {
		return nil, err
	}
	return app, nil
}

// GetBrandIDByAppID 根据AppID获取品牌ID
func (d *Dao) GetBrandMiniAppRefByBrandIDAndPlatform(ctx context.Context, brandID int64, platform int32) (*model.BrandMiniApp, error) {
	app := new(model.BrandMiniApp)
	err := d.FromContext(ctx).Where("brand_id = ? AND platform = ?", brandID, platform).First(app).Error
	if err != nil {
		return nil, err
	}
	return app, nil
}

// BrandMiniAppRef 删除版本品牌关联
func (d *Dao) BrandMiniAppRef(ctx context.Context, brandID int64, appID string, platform int32) error {
	return d.FromContext(ctx).
		Where("app_id = ? and platform = ? and brand_id = ?", appID, platform, brandID).
		Delete(&model.BrandMiniApp{}).Error
}
